package com.atguigu.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
@WebFilter({"/index.jsp","/password.jsp"})
public class CheckLoginFilter extends HttpFilter {
    /**
     * 验证用户是否登录检查session中是否存在user
     * 如果已经登录,那么就放行请求
     * 未登录就跳转
     */
      @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            //要跳转
            request.setAttribute("loginMsg","no");
            request.getRequestDispatcher("/login.jsp").forward(request, response);

        }else {
            chain.doFilter(request, response);
        }
    }
}
